// defineStore, ref, computed 已自动引入
// request 需要手动导入
import request from '@/utils/request'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref(null)
  const token = ref(localStorage.getItem('token') || '')
  const permissions = ref([])

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const userName = computed(() => userInfo.value?.name || '未知用户')
  const userRoles = computed(() => userInfo.value?.roles || [])

  // 操作
  const setToken = newToken => {
    token.value = newToken
    if (newToken) {
      localStorage.setItem('token', newToken)
    } else {
      localStorage.removeItem('token')
    }
  }

  const setUserInfo = info => {
    userInfo.value = info
  }

  const setPermissions = perms => {
    permissions.value = perms
  }

  // 登录
  const login = async loginData => {
    const response = await request.post('/auth/login', loginData)
    const { token: newToken, user, permissions: userPermissions } = response

    setToken(newToken)
    setUserInfo(user)
    setPermissions(userPermissions)

    return response
  }

  // 登出
  const logout = async () => {
    try {
      await request.post('/auth/logout')
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      setToken('')
      setUserInfo(null)
      setPermissions([])
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    const response = await request.get('/user/info')
    setUserInfo(response.user)
    setPermissions(response.permissions)
    return response
  }

  // 检查权限
  const hasPermission = permission => {
    return permissions.value.includes(permission)
  }

  // 检查角色
  const hasRole = role => {
    return userRoles.value.includes(role)
  }

  return {
    // 状态
    userInfo,
    token,
    permissions,
    // 计算属性
    isLoggedIn,
    userName,
    userRoles,
    // 操作
    setToken,
    setUserInfo,
    setPermissions,
    login,
    logout,
    fetchUserInfo,
    hasPermission,
    hasRole
  }
})
